layui.use(['layer', 'form', 'table', 'util', 'admin', 'zTree','laypage','tree','element'], function () {
    var $ = layui.jquery;
    var jQuery = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var laypage = layui.laypage;
    var tree = layui.tree;
    var element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块

    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var fistRenderPage= true;//是否第一次渲染分页

    var roleName = "";//角色名称
    var roleCode = "";//角色代码
    //获取权限方法
    var userInfo = getAuthority()
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getRoleList();
    }

    // 添加
    $('#btnAddRole').click(function () {
        showAddRoleModel();
    });

    //刷新
    $('#btnRefreshRole').click(function () {
        getRoleList();
    });



    // 搜索
    form.on('submit(formSubSearchUser)', function (data) {
        roleName = data.field.roleName;
        roleCode = data.field.roleCode;
        current=1;
        fistRenderPage = true;
        getRoleList();
    });

    // 工具条点击事件
    table.on('tool(tableRole)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            // showEditModel(data);
            showAddRoleModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(obj);
        } else if (layEvent === 'auth') {  // 权限管理
            showPermModel(data.roleId);
        }
    });

    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除“' + obj.data.roleName + '”角色吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:systemUrl.role.deleteRole+obj.data.roleId,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getRoleList();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    // 权限管理
    function showPermModel(roleId) {
        admin.open({
            title: '角色权限分配',
            btn: ['保存', '取消'],
            content: '<ul id="treeAuth" class="ztree"></ul>',
            success: function (layero, index) {
                $(layero).children('.layui-layer-content').css({'max-height': '300px', 'overflow': 'auto'});
                layer.load(2);
                var setting = {check: {enable: true}, data: {simpleData: {enable: true}}};
                $.get('../../json/authTree.json', {
                    roleId: roleId
                }, function (res) {
                    $.fn.zTree.init($('#treeAuth'), setting, res);
                    layer.closeAll('loading');
                }, 'json');
            },
            yes: function (index) {
                layer.load(2);
                var treeObj = $.fn.zTree.getZTreeObj('treeAuth');
                var nodes = treeObj.getCheckedNodes(true);
                var ids = new Array();
                for (var i = 0; i < nodes.length; i++) {
                    ids[i] = nodes[i].id;
                }
                $.get('../../json/ok.json', {
                    roleId: roleId,
                    authIds: JSON.stringify(ids)
                }, function (res) {
                    layer.closeAll('loading');
                    if (200 == res.code) {
                        layer.msg(res.msg, {icon: 1});
                        layer.close(index);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            }
        });
    }

    //获取角色列表
    function getRoleList() {
        var req={
            current: current,
            size: pageSize,
            roleName:roleName,
            roleCode:roleCode
        };
        axios.get(systemUrl.role.roleList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderTable(data);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //渲染表格
    function renderTable(data){
        table.render({
            elem: '#tableRole',
            cellMinWidth: 100,
            data:data.records,
            cols: [[
                {type: 'numbers', title: '#'},
                {field: 'roleName', sort: true, title: '角色名称'},
                {field: 'roleCode', sort: true, title: '角色代码'},
                {
                    templet: function (d) {
                    return util.toDateString(d.createTime);
                }, title: '创建时间'
                },
                {align: 'center', toolbar: '#tableBarRole', title: '操作', minWidth: 200}
            ]]
        });

        //第一次才渲染分页
        if(fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: data.total,
                limit:pageSize,
                groups:1,
                current:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getRoleList();
                    }
                }
            });
        }
    }

    //显示添加角色弹窗
    function showAddRoleModel(mRole) {
        admin.open({
            type: 1,
            title: (mRole ? '编辑' : '新增') + '角色',
            area: ['600px', '700px'],
            content: $('#addRoleModel').html(),
            success: function (layero, dIndex) {
                var ztreeSetting = {
                    check: {
                        enable: true//显示复选框
                    },
                    data: {
                        simpleData: {
                            enable: true//使用简单数据模式(Array)
                        }
                    },
                    view: {
                        showIcon: false
                    }
                };
                if(mRole){//编辑
                    getRoleInfo(mRole.roleId,function (roleInfo) {
                        getPermissionTree(roleInfo.sysPermissionIds,function (permissionTreeData) {
                            getMenuTreeData(roleInfo.sysResourceIds,function (treeData) {
                                //菜单树渲染
                                $.fn.zTree.init($("#roleMenuTree"), ztreeSetting, treeData);
                                //权限树渲染
                                $.fn.zTree.init($("#permissionTree"), ztreeSetting, permissionTreeData);
                                // 回显数据
                                form.val('addRoleForm', roleInfo);
                                // 编辑用户
                                form.on('submit(addRoleSubmit)', function (data) {
                                    layer.load(2);
                                    //获得选中的节点
                                    var treeObj = $.fn.zTree.getZTreeObj("roleMenuTree");
                                    var checkedNodes = treeObj.getCheckedNodes(true);
                                    var sysResourceIds=[];
                                    initTreeCheckData(checkedNodes,sysResourceIds);

                                    //获取权限选中节点
                                    var permissionTree_treeObj = $.fn.zTree.getZTreeObj("permissionTree");
                                    var permissionTree_checkedNodes = permissionTree_treeObj.getCheckedNodes(true);
                                    var sysPermissionIds=[];
                                    initTreeCheckData(permissionTree_checkedNodes,sysPermissionIds);

                                    roleInfo.sysResourceIds = sysResourceIds;
                                    roleInfo.sysPermissionIds = sysPermissionIds;
                                    roleInfo.roleName = data.field.roleName;
                                    roleInfo.roleCode = data.field.roleCode;

                                    axios({
                                        method: 'PUT',
                                        url:systemUrl.role.deleteRole,
                                        data:roleInfo,
                                        headers:{
                                            'Authorization':Authorization
                                        }
                                    })
                                        .then(function (res) {
                                            if (res.status == 200&&res.data.message=="success") {
                                                layer.close(dIndex);
                                                layer.msg("修改成功", {icon: 1});
                                                getRoleList();
                                            } else {
                                                layer.msg(res.data.message, {icon: 2});
                                            }
                                            layer.closeAll('loading');
                                        })
                                        .catch(function (err) {
                                            console.log(err);
                                        })
                                    return false;
                                });
                            })
                        })
                    })
                }else{//新增
                    getPermissionTree([],function (permissionTreeData) {
                        getMenuTreeData([],function (treeData) {
                            //菜单树渲染
                            $.fn.zTree.init($("#roleMenuTree"), ztreeSetting, treeData);
                            //权限树渲染
                            $.fn.zTree.init($("#permissionTree"), ztreeSetting, permissionTreeData);
                            // 新增用户
                            form.on('submit(addRoleSubmit)', function (data) {
                                layer.load(2);
                                //获得菜单选中的节点
                                var treeObj = $.fn.zTree.getZTreeObj("roleMenuTree");
                                var checkedNodes = treeObj.getCheckedNodes(true);
                                var sysResourceIds=[];
                                initTreeCheckData(checkedNodes,sysResourceIds);

                                //获取权限选中节点
                                var permissionTree_treeObj = $.fn.zTree.getZTreeObj("permissionTree");
                                var permissionTree_checkedNodes = permissionTree_treeObj.getCheckedNodes(true);
                                var sysPermissionIds=[];
                                initTreeCheckData(permissionTree_checkedNodes,sysPermissionIds);
                                var req={
                                    sysResourceIds:sysResourceIds,
                                    sysPermissionIds:sysPermissionIds,
                                    roleName:data.field.roleName,
                                    roleCode:data.field.roleCode,
                                    createTime:null,
                                    modifyTime:null,
                                    modifyTome:null,
                                    roleId:null
                                }
                                axios({
                                    method: 'POST',
                                    url:systemUrl.role.deleteRole,
                                    data:req,
                                    headers:{
                                        'Authorization':Authorization
                                    }
                                })
                                    .then(function (res) {
                                        if (res.status == 200&&res.data.message=="success") {
                                            layer.close(dIndex);
                                            layer.msg("新增成功", {icon: 1});
                                            getRoleList();
                                        } else {
                                            layer.msg(res.data.message, {icon: 2});
                                        }
                                        layer.closeAll('loading');
                                    })
                                    .catch(function (err) {
                                        console.log(err);
                                    })
                                return false;
                            });
                        })
                    });
                }
            }
        });
    }
    
    //获取菜单集合数据
    function getMenuTreeData(sysResourceIds,callback) {
        axios.get(systemUrl.role.resourceTree,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr=[];
                    zhuanHuanTree(data,sysResourceIds,resArr);
                    callback(resArr);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //转换菜单集合数据
    function zhuanHuanTree(tdata,sysResourceIds,resData) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(v,i){
                var newValue=v.name;
                resData[i]=v;
                resData[i].title=newValue;
                resData[i].icon = "";
                if(sysResourceIds.includes(v.id)){
                    resData[i].checked = true;
                }else{
                    resData[i].checked = false;
                }
                var arr=[];
                zhuanHuanTree(v.children,sysResourceIds,arr);
                resData[i].children=arr;
            });
        }
    }

    //转换选中的菜单树数据，获取ID
    function initTreeCheckData(tdata,resData) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(v,i){
                resData.push(v.id);
                // initTreeCheckData(v.children,resData);
            });
        }
    }

    //获取角色信息
    function getRoleInfo(id,callback) {
        axios({
            method: 'get',
            url:systemUrl.role.deleteRole+id,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (res) {
                if (res.status == 200&&res.data.message=="success") {
                    callback(res.data.data)
                } else {
                    layer.msg(res.data.message, {icon: 2});
                }
            })
            .catch(function (err) {
                console.log(err);
            })
    }

    //获取权限树数据
    function getPermissionTree(sysPermissionIds,callback) {
        axios.get(systemUrl.permission.permissionTree,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr = [];
                    zhuanHuanTree(data,sysPermissionIds,resArr);
                    callback(resArr)
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

});